import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/http/api';
import aes from "@/utils/aes";

export const useSettingStore = defineStore('setting', () => {
  const setting = ref(null);
  const loading = ref(false);

  const getSetting = async() => {
    if (setting.value != null) {
      return setting.value;
    } else {
      return await loadSetting();
    }
  };

  const loadSetting = async() => {
    if (setting.value != null) {
      loading.value = false;
      return setting.value;
    }

    if (loading.value) {
      await sleep(100);
      return await loadSetting();
    }

    loading.value = true;
    if (setting.value != null) {
      loading.value = false;
      return setting.value;
    } else {
      const res = await api.post('/setting').catch(() => {
        loading.value = false;
      });
      loading.value = false;
      if (res.code === '1') {
        if (res.data && res.data.token && res.data.sha) {
          setting.value = JSON.parse(aes.aesDecrypt(res.data.token, res.data.sha));
        }
        return setting.value;
      }
    }
  };

  const sleep = async(time) => {
    return new Promise((resolve) => setTimeout(resolve, time));
  };

  const clearSetting = () => {
    setting.value = null;
  };

  return { getSetting, clearSetting };
});
